/**
 * 职位管理模块 - 处理职位列表、编辑、发布等功能
 */
class JobManagement {
  constructor() {
    // 初始化DOM元素
    this.initElements();
    // 绑定事件监听
    this.bindEvents();
    // 加载职位数据
    this.loadJobData();
  }

  /**
   * 初始化DOM元素
   */
  initElements() {
    this.jobListContainer = document.getElementById('job-list-container');
    this.editModal = document.getElementById('edit-modal');
    this.editJobForm = document.getElementById('edit-job-form');
    this.closeEditModalBtn = document.querySelector('.close-btn');
    this.sidebarItems = document.querySelectorAll('.sidebar-item');
  }

  /**
   * 绑定事件监听
   */
  bindEvents() {
    // 模块切换事件
    this.sidebarItems.forEach(item => {
      item.addEventListener('click', () => this.switchModule(item));
    });

    // 编辑表单提交事件
    if (this.editJobForm) {
      this.editJobForm.addEventListener('submit', (e) => this.handleFormSubmit(e));
    }

    // 关闭编辑弹窗事件
    if (this.closeEditModalBtn) {
      this.closeEditModalBtn.addEventListener('click', () => this.closeEditModal());
    }
  }

  /**
   * 切换模块显示
   * @param {HTMLElement} item - 侧边栏项目元素
   */
  switchModule(item) {
    const moduleId = item.dataset.module;
    // 隐藏所有模块
    document.querySelectorAll('.module').forEach(module => {
      module.style.display = 'none';
    });
    // 显示选中模块
    const activeModule = document.getElementById(moduleId);
    if (activeModule) {
      activeModule.style.display = 'block';
    }
    // 更新侧边栏选中状态
    this.sidebarItems.forEach(i => i.classList.remove('active'));
    item.classList.add('active');
  }

  /**
   * 加载职位数据
   */
  loadJobData() {
    // 模拟API请求
    fetch('http://localhost:3001/api/jobs', {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    .then(response => response.json())
    .then(result => {
      if (result.success && result.data) {
        this.renderJobTable(result.data);
      } else {
        this.jobListContainer.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无职位数据</td></tr>';
      }
    })
    .catch(error => {
      console.error('加载职位列表失败:', error);
      this.jobListContainer.innerHTML = '<tr><td colspan="7" style="text-align: center;">加载失败，请刷新页面重试</td></tr>';
    });
  }

  /**
   * 渲染职位表格
   * @param {Array} jobs - 职位数据数组
   */
  renderJobTable(jobs) {
    if (!this.jobListContainer) return;

    const tableHtml = `
      <table class="job-table">
        <thead>
          <tr>
            <th>职位名称</th>
            <th>工作类型</th>
            <th>工作地点</th>
            <th>薪资范围</th>
            <th>发布时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          ${jobs.length === 0 ? 
            '<tr><td colspan="7" style="text-align: center;">暂无职位数据</td></tr>' : 
            jobs.map(job => this.createJobRow(job)).join('')}
        </tbody>
      </table>
    `;

    this.jobListContainer.innerHTML = tableHtml;
    // 绑定表格行事件
    this.bindJobRowEvents();
  }

  /**
   * 创建职位表格行
   * @param {Object} job - 职位数据对象
   * @returns {string} 表格行HTML
   */
  createJobRow(job) {
    return `
      <tr data-id="${job.id}">
        <td class="job-name">${job.title}</td>
        <td>${job.jobType === 'full-time' ? '全职' : job.jobType === 'part-time' ? '兼职' : '实习'}</td>
        <td>${job.location}</td>
        <td>${job.salaryRange}</td>
        <td>${new Date(job.createdAt).toLocaleDateString()}</td>
        <td class="job-status ${job.status === 'active' ? 'status-active' : 'status-inactive'}">
          ${job.status === 'active' ? '已上架' : '已下架'}
        </td>
        <td>
          <div class="action-buttons">
            <button class="action-btn edit-btn" data-id="${job.id}">编辑</button>
            <button class="action-btn delete-btn" data-id="${job.id}">删除</button>
            <button class="action-btn toggle-btn" data-id="${job.id}" data-status="${job.status}">
              ${job.status === 'active' ? '下架' : '上架'}
            </button>
          </div>
        </td>
      </tr>
    `;
  }

  /**
   * 绑定职位表格行事件
   */
  bindJobRowEvents() {
    // 编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.addEventListener('click', () => this.openEditModal(btn.dataset.id));
    });

    // 删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', () => this.deleteJob(btn.dataset.id));
    });

    // 状态切换按钮事件
    document.querySelectorAll('.toggle-btn').forEach(btn => {
      btn.addEventListener('click', () => this.toggleJobStatus(btn.dataset.id, btn.dataset.status));
    });
  }

  /**
   * 打开编辑弹窗
   * @param {string} jobId - 职位ID
   */
  openEditModal(jobId) {
    // 加载职位详情
    fetch(`http://localhost:3001/api/jobs/${jobId}`, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    .then(response => response.json())
    .then(result => {
      if (result.success && result.data) {
        this.populateEditForm(result.data);
        this.editModal.style.display = 'flex';
      }
    });
  }

  /**
   * 填充编辑表单
   * @param {Object} job - 职位数据
   */
  populateEditForm(job) {
    document.getElementById('edit-job-title').value = job.title || '';
    document.getElementById('edit-salary-range').value = job.salaryRange || '';
    document.getElementById('edit-location').value = job.location || '';
    document.getElementById('edit-urgency').value = job.urgency || '普通';
    document.getElementById('edit-job-description').value = job.description || '';
    document.getElementById('edit-requirements').value = job.requirements || '';
    document.getElementById('edit-benefits').value = job.benefits || '';
    document.getElementById('edit-highlights').value = job.highlights || '';
    // 存储当前编辑的职位ID
    this.currentJobId = job.id;
  }

  /**
   * 关闭编辑弹窗
   */
  closeEditModal() {
    this.editModal.style.display = 'none';
    // 重置表单验证状态
    document.querySelectorAll('.form-group').forEach(group => {
      group.classList.remove('validation-error');
    });
  }

  /**
   * 处理表单提交
   * @param {Event} e - 事件对象
   */
  handleFormSubmit(e) {
    e.preventDefault();
    if (this.validateForm()) {
      const formData = this.collectFormData();
      this.saveJob(formData);
    }
  }

  /**
   * 验证表单
   * @returns {boolean} 是否验证通过
   */
  validateForm() {
    let isValid = true;
    const title = document.getElementById('edit-job-title').value.trim();
    const salary = document.getElementById('edit-salary-range').value.trim();
    const location = document.getElementById('edit-location').value.trim();
    const description = document.getElementById('edit-job-description').value.trim();
    const requirements = document.getElementById('edit-requirements').value.trim();

    // 职位名称验证
    if (!title) {
      this.showError('edit-job-title', '请输入职位名称');
      isValid = false;
    } else {
      this.hideError('edit-job-title');
    }

    // 薪资格式验证
    const salaryRegex = /^\d+k?-\d+k?$/;
    if (!salary || !salaryRegex.test(salary)) {
      this.showError('edit-salary-range', '请输入有效的薪资范围（如：10k-20k）');
      isValid = false;
    } else {
      this.hideError('edit-salary-range');
    }

    // 工作地点验证
    if (!location) {
      this.showError('edit-location', '请输入工作地点');
      isValid = false;
    } else {
      this.hideError('edit-location');
    }

    // 岗位描述验证
    if (!description) {
      this.showError('edit-job-description', '请输入岗位描述');
      isValid = false;
    } else {
      this.hideError('edit-job-description');
    }

    // 任职要求验证
    if (!requirements) {
      this.showError('edit-requirements', '请输入任职要求');
      isValid = false;
    } else {
      this.hideError('edit-requirements');
    }

    return isValid;
  }

  /**
   * 显示错误提示
   * @param {string} fieldId - 字段ID
   * @param {string} message - 错误消息
   */
  showError(fieldId, message) {
    const field = document.getElementById(fieldId);
    const errorElement = field.nextElementSibling;
    field.parentElement.classList.add('validation-error');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
  }

  /**
   * 隐藏错误提示
   * @param {string} fieldId - 字段ID
   */
  hideError(fieldId) {
    const field = document.getElementById(fieldId);
    const errorElement = field.nextElementSibling;
    field.parentElement.classList.remove('validation-error');
    errorElement.style.display = 'none';
  }

  /**
   * 收集表单数据
   * @returns {Object} 表单数据对象
   */
  collectFormData() {
    return {
      title: document.getElementById('edit-job-title').value.trim(),
      salaryRange: document.getElementById('edit-salary-range').value.trim(),
      location: document.getElementById('edit-location').value.trim(),
      urgency: document.getElementById('edit-urgency').value,
      description: document.getElementById('edit-job-description').value.trim(),
      requirements: document.getElementById('edit-requirements').value.trim(),
      benefits: document.getElementById('edit-benefits').value.trim(),
      highlights: document.getElementById('edit-highlights').value.trim()
    };
  }

  /**
   * 保存职位数据
   * @param {Object} data - 职位数据
   */
  saveJob(data) {
    fetch(`http://localhost:3001/api/jobs/${this.currentJobId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        alert('职位信息修改成功');
        this.closeEditModal();
        this.loadJobData(); // 重新加载职位列表
      } else {
        alert('修改失败: ' + (result.message || '未知错误'));
      }
    })
    .catch(error => {
      console.error('保存职位失败:', error);
      alert('保存失败，请重试');
    });
  }

  /**
   * 删除职位
   * @param {string} jobId - 职位ID
   */
  deleteJob(jobId) {
    if (confirm('确定要删除该职位吗？')) {
      fetch(`http://localhost:3001/api/jobs/${jobId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          this.loadJobData(); // 重新加载职位列表
        } else {
          alert('删除失败: ' + (result.message || '未知错误'));
        }
      })
      .catch(error => {
        console.error('删除职位失败:', error);
        alert('删除失败，请重试');
      });
    }
  }

  /**
   * 切换职位状态（上架/下架）
   * @param {string} jobId - 职位ID
   * @param {string} currentStatus - 当前状态
   */
  toggleJobStatus(jobId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    fetch(`http://localhost:3001/api/jobs/${jobId}/status`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify({ status: newStatus })
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        this.loadJobData(); // 重新加载职位列表
      } else {
        alert('状态更新失败: ' + (result.message || '未知错误'));
      }
    })
    .catch(error => {
      console.error('更新职位状态失败:', error);
      alert('状态更新失败，请重试');
    });
  }
}

// 页面加载完成后初始化职位管理模块
document.addEventListener('DOMContentLoaded', () => {
  // 只有在职位管理页面才初始化
  if (document.querySelector('#job-management')) {
    new JobManagement();
  }
});